package com.bot.nft.module.mb.service.impl;

import cn.hutool.core.bean.BeanUtil;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bot.common.util.CommonCryptogramUtil;
import com.bot.nft.core.config.LoginStorage;
import com.bot.nft.core.config.RandomNameGen;
import com.bot.nft.core.enums.cm.Enum;
import com.bot.nft.core.enums.mb.MbEnum;
import com.bot.nft.module.cm.domain.CmNoticeInfo;
import com.bot.nft.module.mb.domain.MbUserInfo;
import com.bot.nft.module.mb.domain.bo.LoginQueryBo;
import com.bot.nft.module.mb.domain.bo.MbUserInfoBo;
import com.bot.nft.module.mb.domain.vo.MbUserInfoVo;
import com.bot.nft.module.mb.mapper.IMbMemberMapper;
import com.bot.nft.module.mb.service.IMbMemberService;
import net.jodah.expiringmap.ExpiringMap;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


/**
 * 描述: 会员实现类
 * <p>
 * 时间: 2023-11-30 11:17
 * 负责人: 卢梦丽
 **/
@Service
public class MbMemberServiceImpl extends ServiceImpl<IMbMemberMapper, MbUserInfo> implements IMbMemberService {

    @Resource
    private IMbMemberMapper iMbMemberMapper;

    @Override
    public Boolean addMemberMbInfo(MbUserInfoBo memberMbInfoBo) {
        memberMbInfoBo.setId(IdUtil.getSnowflakeNextIdStr());
        memberMbInfoBo.setCreateTime(new Date());
        MbUserInfo mbUserInfo = BeanUtil.toBean(memberMbInfoBo, MbUserInfo.class);
        mbUserInfo.setDeleteFlag(MbEnum.NODEL.getName());
        mbUserInfo.setIsKyc(0);//默认未实名
        if (mbUserInfo.getUserStatus().equals("")){
            mbUserInfo.setUserStatus(MbEnum.END.getName());
        }

        int insert = iMbMemberMapper.insert(mbUserInfo);
        Boolean msg = false;
        if (insert==1){
            msg = true;
        }
        return msg;
    }

    @Override
    public Boolean updateMemberMbInfo(MbUserInfoBo memberMbInfoBo) {
        MbUserInfo mbUserInfo = BeanUtil.toBean(memberMbInfoBo, MbUserInfo.class);
        int i = iMbMemberMapper.updateById(mbUserInfo);
        Boolean msg = false;
        if (i==1){
            msg = true;
        }
        return msg;
    }

    @Override
    public MbUserInfoVo getMemberMbInfo(String id) {


        MbUserInfoVo mbUserInfoVo = iMbMemberMapper.selectVoById(id);
        String phone = mbUserInfoVo.getPhone();
        String phoneSM4 = CommonCryptogramUtil.doSm4CbcDecrypt(phone);
        mbUserInfoVo.setPhone(phoneSM4);
        return mbUserInfoVo;
    }

    @Override
    public Boolean delMemberMbInfo(String id) {
        boolean update = this.lambdaUpdate()
                .set(MbUserInfo::getDeleteFlag, MbEnum.ALDEL.getName())
                .eq(MbUserInfo::getId,id)
                .update();
        return update;
    }

    @Override
    public Page<MbUserInfoVo> queryMemberByPage(String keyword, Integer userStatus, Integer pageNo, Integer pageSize) {
        //开启分页
        Page<MbUserInfo> page = new Page<>(pageNo, pageSize);
        QueryWrapper<MbUserInfo> queryWrapper = new QueryWrapper<>();
        //判断关键字不为空
        if (!StringUtils.isEmpty(keyword)) {
            queryWrapper.lambda().like(MbUserInfo::getNickname, keyword);
        }
        //判断状态不为空
        if (null != userStatus) {
            queryWrapper.lambda().like(MbUserInfo::getUserStatus, userStatus);
        }
        queryWrapper.lambda().like(MbUserInfo::getDeleteFlag, MbEnum.NODEL.getName());
        queryWrapper.lambda().orderByDesc(MbUserInfo::getCreateTime);
        //查询结果
        Page<MbUserInfoVo> mbUserInfoPage = iMbMemberMapper.selectVoPage(page, queryWrapper);
        List<MbUserInfoVo> records = mbUserInfoPage.getRecords();
        for (int i = 0;i<records.size();i++){
            MbUserInfoVo mbUserInfoVo = records.get(i);
            String phone = mbUserInfoVo.getPhone();//获取手机号
            String phoneSM4 = CommonCryptogramUtil.doSm4CbcDecrypt(phone);//解密手机号
            mbUserInfoVo.setPhone(phoneSM4);
        }


        return mbUserInfoPage;
    }

    @Override
    public Boolean startMemberMbInfo(String id) {
        boolean update = this.lambdaUpdate()
                .set(MbUserInfo::getUserStatus, MbEnum.START.getName())
                .eq(MbUserInfo::getId,id)
                .update();
        return update;
    }

    @Override
    public Boolean disMemberMbInfo(String id) {
        boolean update = this.lambdaUpdate()
                .set(MbUserInfo::getUserStatus, MbEnum.END.getName())
                .eq(MbUserInfo::getId,id)
                .update();
        return update;
    }

    @Override
    public Boolean regAccountMbInfo(MbUserInfoBo memberMbInfoBo) {
        return null;
    }

    @Override
    public MbUserInfoVo getMbInfoUniApp(String phone) {
        MbUserInfoVo mbUserInfoVo = iMbMemberMapper.selectVoById(phone);

        String password = CommonCryptogramUtil.doSm4CbcDecrypt(mbUserInfoVo.getPhone());
        mbUserInfoVo.setPhone(password);
        return mbUserInfoVo;
    }

    @Override
    public Boolean addPwdUniApp(String id, String password) {
        boolean update = this.lambdaUpdate()
                .set(MbUserInfo::getPassword,password)
                .eq(MbUserInfo::getId,id)
                .update();
        return update;

    }

    @Override
    public Boolean updateNick(String id, String nickName) {
        boolean update = this.lambdaUpdate()
                .set(MbUserInfo::getNickname,nickName)
                .eq(MbUserInfo::getId,id)
                .update();
        return update;

    }

    @Override
    public Boolean updateAvatar(String id, String avatar, String uuidAvatar) {

        boolean update = this.lambdaUpdate()
                .set(MbUserInfo::getAvatar,avatar)
                .set(MbUserInfo::getUuidAvatar,uuidAvatar)
                .eq(MbUserInfo::getId,id)
                .update();
        return update;

    }

    /**
     * 手机号验证
     *
     * @param phone 手机号
     * @return 是否成功
     */
    @Override
    public Boolean sendcode(String phone) {
        //限制发送验证码次数
        ExpiringMap<String, Integer> expiringMap = LoginStorage.getExpiringMap();
        //获取验证码次数
        Integer integer = expiringMap.get(phone);
        //如果验证次数为空
        if (integer == null) {
            expiringMap.put("verify" + phone, 1, 1, TimeUnit.DAYS);
        } else if (integer > 10) {//验证次数大于10
            throw new RuntimeException("发送验证码次数上限");
        } else {
            expiringMap.put("verify" + phone, ++integer);
        }
        //生成随机验证码
        Random random = new Random();
        double v = random.nextDouble();
        double dou = 1.0 + (v * 9.0);
        Integer code = (int) (dou * 100000);
        //存储手机号和验证码（并设置超时时间）
        expiringMap.put("code" + phone, code, 30, TimeUnit.MINUTES);
        //短信验证
//        Boolean aBoolean = SmsUtils.smsCode(phone, code);
        System.out.println(code);
        return true;
    }

    /**
     * 登录
     *
     * @param loginQueryBo 登录信息
     * @return
     */
    @Override
    public String mbLogin(LoginQueryBo loginQueryBo) {

        String token = "";
        //获取手机号
        String phone = loginQueryBo.getPhone();
        //获取验证码
        Integer code = loginQueryBo.getCode();
        //调用工具看手机号是否存储在里面
        ExpiringMap<String, Integer> expiringMap = LoginStorage.getExpiringMap();
        Integer integer = expiringMap.get("code" + phone);
        //此手机号没有验证码或超时验证码失效
        if (null == integer) {
            throw new RuntimeException("验证码失效");
        }
        //验证码不相同
        if (!code.equals(integer)) {
            throw new RuntimeException("验证码错误");
        }
        //验证码相同
        if (code.equals(integer)) {
            //调用根据手机号查看会员信息的mapper接口
            QueryWrapper<MbUserInfo> mbUserInfoQueryWrapper = new QueryWrapper<>();
            mbUserInfoQueryWrapper.lambda().eq(MbUserInfo::getPhone, phone);
            MbUserInfoVo mbUserInfoVo = iMbMemberMapper.selectVoOne(mbUserInfoQueryWrapper);
            //会员不存在
            if (ObjectUtil.isEmpty(mbUserInfoVo)) {
                MbUserInfo mbMemberInfo = new MbUserInfo();
                mbMemberInfo.setId(IdUtil.getSnowflakeNextIdStr());
                mbMemberInfo.setAvatar("");
                mbMemberInfo.setAccount(RandomNameGen.gener());
                mbMemberInfo.setNickname(RandomNameGen.gener());
                mbMemberInfo.setPhone(phone);
                mbMemberInfo.setCreateTime(new Date());
                mbMemberInfo.setIsKyc(0);
                mbMemberInfo.setUserStatus(MbEnum.START.getName());
                mbMemberInfo.setDeleteFlag(MbEnum.NODEL.getName());
                //添加会员信息
                iMbMemberMapper.insert(mbMemberInfo);
            }
            if (!ObjectUtil.isEmpty(mbUserInfoVo)) {
                //获取会员状态
                String userStatus = mbUserInfoVo.getUserStatus();
                //会员账号被禁用
                if (userStatus.equals(0)) {
                    throw new RuntimeException("账号被禁用");
                }
                //会员账号为启用状态
                if (userStatus.equals(1)) {
                    //生成一个令牌
                    token = UUID.randomUUID().toString();
                    //用户登录
                    ExpiringMap<String, MbUserInfoVo> userMap = LoginStorage.getUserMap();
                    //存储用户信息
                    userMap.put(token, mbUserInfoVo);
                }
            }
        }
        return token;
    }

    @Override
    public Integer userNameNum(String userName) {
        Integer userNameNum = iMbMemberMapper.userNameNum(userName);
        return userNameNum;
    }

    @Override
    public Integer phoneNum(String phone) {
        Integer phoneNum = iMbMemberMapper.phoneNum(phone);

        return phoneNum;
    }


}
